package com.miage.itrading.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ConnecteurBDD {

	private static final String	DATABASE	= Const.DATABASE_URL;
	private static final String	USER		= Const.DATABASE_USERNAME;
	private static final String	PASSWORD	= Const.DATABASE_PASSWORD;

	private static Connection	Conn;

	private static Connection getConn()
	{
		connecte();
		return Conn;
	}
	
	private static Connection connecte() {
		if (Conn == null) {
			try {
				DriverManager.registerDriver(new com.mysql.jdbc.Driver());
				Conn = DriverManager.getConnection(DATABASE, USER, PASSWORD);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return Conn;
	}
	
	public static ResultSet executeQuery(String sql) throws SQLException
	{
		outSql(sql);
		ResultSet rs = null;
		try {
			rs = getConn().createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY)
				.executeQuery(sql);
		} catch (SQLException e) {
			outSql(sql, true);
			throw e;
		}

		return rs;
	}
	
	public static void executeUpdate(String sql) throws SQLException
	{
		outSql(sql);
		getConn().createStatement().executeUpdate(sql);
	}
	
	public static ResultSet executeUpdateReturn(String sql) throws SQLException
	{
		outSql(sql);
		Statement stat = getConn().createStatement();
		stat.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

		return stat.getGeneratedKeys();
	}
	
	private static void outSql(String sql)
	{
		if(Const.SHOW_SQL)
			System.out.println(sql);
	}
	
	private static void outSql(String sql, boolean force)
	{
		if(!Const.SHOW_SQL)
			System.out.println(sql);
	}
}